package com.aiti.lulian.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.constant.MiniProgramVersionConstant;
import com.aiti.lulian.constant.SupplyToCRMConstant;
import com.aiti.lulian.dto.crm.SupplyToCRMParamDto;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.feign.LulianSubService;
import com.aiti.lulian.mapper.*;
import com.aiti.lulian.service.*;
import com.aiti.lulian.vo.crm.SourcingDemandVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * description:
 * auth fcb
 * date 2025-05-19 18:02
 **/
@Service
@Slf4j
public class SupplyToCRMServiceImpl implements SupplyToCRMService {

    // 个人手机号
    private static final Pattern PHONE_PATTERN = Pattern.compile("1[3-9]\\d{9}");
    // 座机号码
    private static final Pattern PHONE_TEL = Pattern.compile("0\\d{2,3}[- ]?\\d{7,8}");

    @Autowired
    private CommunicateInfoMapper communicateInfoMapper;
    @Autowired
    private ILuLianSourcingDemandMapper sourcingDemandMapper;
    @Autowired
    private CustomerManagementMapper customerManagementMapper;
    @Autowired
    private ILuLianRecruitmentService luLianRecruitmentService;
    @Autowired
    private LulianSubService lulianSubService;
    @Autowired
    private SysAreaMapper sysAreaMapper;
    @Autowired
    private ILuLianSupplierInquiryOrderService luLianSupplierInquiryOrderService;
    @Autowired
    private ILuLianEnterpriseUserService luLianEnterpriseUserService;
    @Autowired
    private ILuLianEnterpriseService luLianEnterpriseService;
    @Autowired
    private CloudShowManagerSubService cloudShowManagerSubService;
    @Autowired
    private ILuLianSupplierInquiryOrderRequestMapper luLianSupplierInquiryOrderRequestMapper;
    @Autowired
    private ICustomerContactsService customerContactsService;

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void addSupplyToCRM(SupplyToCRMParamDto supplyToCRMParamDto, String userId) {
        this.checkAddCRMParam(supplyToCRMParamDto);
        // 1. 判断商机是否已经存在
//        Integer communicateInfoCount = communicateInfoMapper.queryCommunicateCountBySupplyId(supplyToCRMParamDto.getBaseId(),  supplyToCRMParamDto.getCompanyId());
        Integer communicateInfoCount = isExist(supplyToCRMParamDto);
        if(communicateInfoCount > 0) {
            throw new BusinessException("该商机已经存在");
        }
        Message userInfoMessage = cloudShowManagerSubService.getUserInfo(userId);
        if (userInfoMessage.getCode() != MessageCodeConstant.MSG_SUCCESS_CODE) {
            throw new BusinessException("获取用户信息失败");
        }
        Object obj = userInfoMessage.getObj();
        if (obj == null) {
            throw new BusinessException("获取用户信息异常");
        }
        Map<String, Object> userInfoMap = (Map<String, Object>) obj;
        log.info("用户信息：{}", userInfoMap);
        String realname = (String) userInfoMap.get("realname");
        String deptId = (String)userInfoMap.get("deptId");
        String deptName = (String)userInfoMap.get("deptName");
        supplyToCRMParamDto.setDeptId(deptId);
        supplyToCRMParamDto.setDeptName(deptName);
        LuLianEnterprise luLianEnterprise = luLianEnterpriseService.getById(supplyToCRMParamDto.getCompanyId());
        if(luLianEnterprise == null) {
            throw new BusinessException("用户所属企业不存在");
        }else{
            supplyToCRMParamDto.setCompanyName(luLianEnterprise.getBaseName());
        }
        // 2. 创建客户和商机
        if(SupplyToCRMConstant.SOURCE_FROM_1.equals(supplyToCRMParamDto.getSourceFrom())) {
            // 2.0 询价单商机详情
            SourcingDemandVo sourcingDemandVo = sourcingDemandMapper.queryBySourcingDemandByBaseId(supplyToCRMParamDto.getBaseId());
            if(sourcingDemandVo == null) {
                throw new BusinessException("该商机不存在");
            }
            // 2.1.1 判断客户是否存在，不存在则先创建客户
            String customerBaseId = customerManagementMapper.queryCustomerCountBySupplyId(supplyToCRMParamDto.getBaseId(), supplyToCRMParamDto.getCompanyId());
            if(StrUtil.isEmpty(customerBaseId)) {
                // 创建客户
                CustomerManagement customerManagement = this.buildCustomerManagementBySourcingDemand(sourcingDemandVo, supplyToCRMParamDto, userId);
                customerBaseId = customerManagement.getBaseId();
                customerManagementMapper.insert(customerManagement);
            }
            // 2.1.2 创建联系人，并将其与客户进行关联
            customerContactsService.createContactAndRelation(sourcingDemandVo.getContacts(), sourcingDemandVo.getPhone(), customerBaseId, userId, supplyToCRMParamDto.getCompanyId(), supplyToCRMParamDto);
            // 2.2 创建商机
            CommunicateInfo communicateInfo = this.buildCommunicateInfoBySourcingDemand(sourcingDemandVo, supplyToCRMParamDto, customerBaseId, userId, realname);
            communicateInfoMapper.insert(communicateInfo);
        }
        // 3. 招募单商机
        else if(SupplyToCRMConstant.SOURCE_FROM_2.equals(supplyToCRMParamDto.getSourceFrom())) {
            // 3.0 招募单详情
            // 先将一类的招募单变量声明出来
            LuLianSupplierInquiryOrder supplierInquiryOrder = null;
            // 查询是否属于另一类的招募单
            LuLianRecruitment recruitment = luLianRecruitmentService.getById(supplyToCRMParamDto.getBaseId());
            if(recruitment == null) {
                supplierInquiryOrder = luLianSupplierInquiryOrderService.getById(supplyToCRMParamDto.getBaseId());
                if (supplierInquiryOrder == null) {
                    throw new BusinessException("该商机不存在");
                }
            }
            // 3.1.1 判断客户是否存在，不存在则先创建客户
            String customerBaseId = customerManagementMapper.queryCustomerCountBySupplyId(supplyToCRMParamDto.getBaseId(), supplyToCRMParamDto.getCompanyId());
            // 先声明下 LuLianSupplierInquiryOrder类招募单 的联系人与联系方式变量
            String contactsName = "";
            String contactsPhone = "";
            if(StrUtil.isEmpty(customerBaseId)) {
                // 创建客户
                CustomerManagement customerManagement;
                if (recruitment != null) {
                    customerManagement = this.buildCustomerManagementByRecruitment(recruitment, supplyToCRMParamDto, userId);
                } else {
                    customerManagement = this.buildCustomerManagementBySupplierInquiryOrder(supplierInquiryOrder, supplyToCRMParamDto, userId);
                    contactsName = customerManagement.getCreatorRealName();
                    contactsPhone = customerManagement.getPhone();
                }
                customerBaseId = customerManagement.getBaseId();
                customerManagementMapper.insert(customerManagement);
            }
            // 3.1.2 创建联系人，并将其与客户进行关联
            if (recruitment != null) {
                customerContactsService.createContactAndRelation(recruitment.getContactName(), recruitment.getContactTel(), customerBaseId, userId, supplyToCRMParamDto.getCompanyId(), supplyToCRMParamDto);
            } else {
                customerContactsService.createContactAndRelation(contactsName, contactsPhone, customerBaseId, userId, supplyToCRMParamDto.getCompanyId(), supplyToCRMParamDto);
            }
            // 3.2 创建商机
            CommunicateInfo communicateInfo;
            if (recruitment != null) {
                communicateInfo = this.buildCommunicateInfoByRecruitment(recruitment, supplyToCRMParamDto, customerBaseId, userId, realname);
            } else {
                communicateInfo = this.buildCommunicateInfoBySupplierInquiryOrder(supplierInquiryOrder, supplyToCRMParamDto, customerBaseId, userId, realname);
            }
            communicateInfoMapper.insert(communicateInfo);
        }
        // 4. 招标信息创建商机
        else if(SupplyToCRMConstant.SOURCE_FROM_3.equals(supplyToCRMParamDto.getSourceFrom())) {
            // 4.0 获取招标信息数据
            Message projectDetailInfo = lulianSubService.getProjectDetailInfo(supplyToCRMParamDto.getBaseId());
            if(MessageCodeConstant.MSG_FAIL_CODE.equals(projectDetailInfo.getCode())) {
                throw new BusinessException("获取招标信息失败");
            }
            Map<String, String> map = (Map<String, String>) projectDetailInfo.getObj();
            // 4.1 判断客户是否存在，不存在则先创建客户
            String customerBaseId = customerManagementMapper.queryCustomerCountBySupplyId(supplyToCRMParamDto.getBaseId(), supplyToCRMParamDto.getCompanyId());
            if(StrUtil.isEmpty(customerBaseId)) {
                CustomerManagement customerManagement = this.buildCustomerManagementByBidInfo(map, supplyToCRMParamDto, userId);
                customerBaseId = customerManagement.getBaseId();
                customerManagementMapper.insert(customerManagement);
            }
            // 创建商机
            CommunicateInfo communicateInfo = this.buildCommunicateInfoByBidInfo(map, supplyToCRMParamDto, customerBaseId, userId, realname);
            communicateInfoMapper.insert(communicateInfo);
        }
        else {
            throw new BusinessException("不支持的商机类型");
        }
    }

    @Override
    public Integer isExist(SupplyToCRMParamDto supplyToCRMParamDto) {
        return communicateInfoMapper.queryCommunicateCountBySupplyId(supplyToCRMParamDto.getBaseId(),  supplyToCRMParamDto.getCompanyId());
    }

    private void checkAddCRMParam(SupplyToCRMParamDto supplyToCRMParamDto) {
        if(StrUtil.isEmpty(supplyToCRMParamDto.getBaseId())) {
            throw new BusinessException("商机id不能为空");
        }
        if(StrUtil.isEmpty(supplyToCRMParamDto.getSupplyUrl())) {
            throw new BusinessException("商机URL地址能为空");
        }
        if(supplyToCRMParamDto.getSourceFrom() == null) {
            throw new BusinessException("商机来源不能为空");
        }
        if(StrUtil.isEmpty(supplyToCRMParamDto.getCompanyId())) {
            throw new BusinessException("公司id不能为空");
        }
        String enterpriseId = supplyToCRMParamDto.getCompanyId();
        LuLianEnterprise luLianEnterprise = luLianEnterpriseService.getById(enterpriseId);
        if(luLianEnterprise == null) {
            throw new BusinessException("公司不存在");
        }else{
            Integer miniProgramVersion = luLianEnterprise.getMiniProgramVersion();
            if(miniProgramVersion != null && !MiniProgramVersionConstant.GaoJiAndTuoKeVersionList.contains(miniProgramVersion)) {
                throw new BusinessException("企业只有开通高级版才可添加线索，请企业管理员先给该企业开通高级版");
            }

        }
    }

    /**
     * 通过询价单创建客户
     * @param sourcingDemandVo 询价单信息
     * @param supplyToCRMParamDto 页面参数
     * @param userId
     * @return
     */
    private CustomerManagement buildCustomerManagementBySourcingDemand(SourcingDemandVo sourcingDemandVo, SupplyToCRMParamDto supplyToCRMParamDto, String userId) {
        CustomerManagement customerManagement = new CustomerManagement();
        customerManagement.setBaseId(IdUtil.simpleUUID());
        customerManagement.setEnterpriseName(sourcingDemandVo.getEnterpriseName());
        customerManagement.setPhone(sourcingDemandVo.getPhone());
        customerManagement.setProvince(sourcingDemandVo.getProvince());
        customerManagement.setCity(sourcingDemandVo.getCity());
        customerManagement.setCounty(sourcingDemandVo.getCounty());
        customerManagement.setCustomerStatus(SupplyToCRMConstant.DEFAULT_CUSTOMER_STATUS);
        customerManagement.setCustomerFrom(supplyToCRMParamDto.getSourceFrom());
        customerManagement.setCustomerFromBaseId(supplyToCRMParamDto.getBaseId());
        customerManagement.setCreator(userId);
        customerManagement.setBaseCreateTime(new Date());
        customerManagement.setCompanyId(supplyToCRMParamDto.getCompanyId());
        customerManagement.setSaleResponsiblePerson(userId);
        customerManagement.setDeptId(supplyToCRMParamDto.getDeptId());
        return customerManagement;
    }

    /**
     * 通过招聘单创建客户
     * @param recruitment 招聘单信息
     * @param supplyToCRMParamDto 页面参数
     * @param userId
     * @return
     */
    private CustomerManagement buildCustomerManagementByRecruitment(LuLianRecruitment recruitment, SupplyToCRMParamDto supplyToCRMParamDto, String userId) {
        CustomerManagement customerManagement = new CustomerManagement();
        customerManagement.setBaseId(IdUtil.simpleUUID());
        customerManagement.setEnterpriseName(recruitment.getCompanyName());
        customerManagement.setPhone(recruitment.getContactTel());
        customerManagement.setProvince(recruitment.getProvince());
        customerManagement.setCity(recruitment.getCity());
        customerManagement.setCounty(recruitment.getCounty());
        customerManagement.setCustomerStatus(SupplyToCRMConstant.DEFAULT_CUSTOMER_STATUS);
        customerManagement.setCustomerFrom(supplyToCRMParamDto.getSourceFrom());
        customerManagement.setCustomerFromBaseId(supplyToCRMParamDto.getBaseId());
        customerManagement.setCreator(userId);
        customerManagement.setBaseCreateTime(new Date());
        customerManagement.setCompanyId(supplyToCRMParamDto.getCompanyId());
        customerManagement.setSaleResponsiblePerson(userId);
        customerManagement.setDeptId(supplyToCRMParamDto.getDeptId());
        return customerManagement;
    }

    private CustomerManagement buildCustomerManagementBySupplierInquiryOrder(LuLianSupplierInquiryOrder supplierInquiryOrder, SupplyToCRMParamDto supplyToCRMParamDto, String userId) {
        CustomerManagement customerManagement = new CustomerManagement();
        customerManagement.setBaseId(IdUtil.simpleUUID());
        String creator = supplierInquiryOrder.getCreator();
        LuLianEnterpriseUser enterpriseUser = luLianEnterpriseUserService.getOne(new LambdaQueryWrapper<LuLianEnterpriseUser>().eq(LuLianEnterpriseUser::getUserId, creator));
        LuLianEnterprise luLianEnterprise = luLianEnterpriseService.getById(enterpriseUser.getEnterpriseId());
        customerManagement.setEnterpriseName(luLianEnterprise.getBaseName());
        Message userInfoMessage = cloudShowManagerSubService.getUserInfo(creator);
        if (userInfoMessage.getCode() != MessageCodeConstant.MSG_SUCCESS_CODE) {
            throw new BusinessException("获取用户信息失败");
        }
        Map<String, Object> userInfoMap = (Map<String, Object>) userInfoMessage.getObj();
        if (userInfoMap == null) {
            throw new BusinessException("获取用户信息异常");
        }
        Object username = userInfoMap.get("username");
        customerManagement.setPhone(username == null ? "" : username.toString());
        LuLianSupplierInquiryOrderRequest supplierInquiryOrderRequest = luLianSupplierInquiryOrderRequestMapper.selectOne(new LambdaQueryWrapper<LuLianSupplierInquiryOrderRequest>().eq(LuLianSupplierInquiryOrderRequest::getOrderId, supplierInquiryOrder.getBaseId()));
        customerManagement.setProvince(supplierInquiryOrderRequest.getRegionProvince());
        customerManagement.setCity(supplierInquiryOrderRequest.getRegionCity());
        customerManagement.setCounty(supplierInquiryOrderRequest.getRegionDistrict());
        customerManagement.setCustomerStatus(SupplyToCRMConstant.DEFAULT_CUSTOMER_STATUS);
        customerManagement.setCustomerFrom(supplyToCRMParamDto.getSourceFrom());
        customerManagement.setCustomerFromBaseId(supplyToCRMParamDto.getBaseId());
        customerManagement.setCreator(userId);
        customerManagement.setBaseCreateTime(new Date());
        customerManagement.setCompanyId(supplyToCRMParamDto.getCompanyId());
        Object realname = userInfoMap.get("realname");
        customerManagement.setCreatorRealName(realname == null ? "" : realname.toString());
        customerManagement.setSaleResponsiblePerson(userId);
        customerManagement.setDeptId(supplyToCRMParamDto.getDeptId());
        return customerManagement;
    }

    private CustomerManagement buildCustomerManagementByBidInfo(Map<String, String> map, SupplyToCRMParamDto supplyToCRMParamDto, String userId) {
        CustomerManagement customerManagement = new CustomerManagement();
        customerManagement.setBaseId(IdUtil.simpleUUID());
//        // 这里的联系人目前无法提取，只能空着
        customerManagement.setEnterpriseName(map.get("companyName"));
        customerManagement.setPhone(this.getPhone(map.get("infoContent")));

        String areaProvinceBaseId = this.getProvinceBaseId(map.get("areaProvince"));
        customerManagement.setProvince(areaProvinceBaseId);

        String areaCityBaseId = this.getCityOrCountyBaseId(map.get("areaCity"), areaProvinceBaseId);
        customerManagement.setCity(areaCityBaseId);
        customerManagement.setCounty(this.getCityOrCountyBaseId(map.get("areaCounty"), areaCityBaseId));

        customerManagement.setCustomerStatus(SupplyToCRMConstant.DEFAULT_CUSTOMER_STATUS);
        customerManagement.setCustomerFrom(supplyToCRMParamDto.getSourceFrom());
        customerManagement.setCustomerFromBaseId(supplyToCRMParamDto.getBaseId());
        customerManagement.setCreator(userId);
        customerManagement.setBaseCreateTime(new Date());
        customerManagement.setCompanyId(supplyToCRMParamDto.getCompanyId());
        customerManagement.setSaleResponsiblePerson(userId);
        customerManagement.setDeptId(supplyToCRMParamDto.getDeptId());
        return customerManagement;
    }

    // 提取联系电话
    private String getPhone(String infoContent) {
        if(StrUtil.isEmpty(infoContent)) {
            return "";
        }
        String phone = "";
        Matcher matcher = PHONE_PATTERN.matcher(infoContent);
        if(matcher.find()) {
            phone = matcher.group();
        }else {
            Matcher matcherTel = PHONE_TEL.matcher(infoContent);
            if(matcherTel.find()) {
                phone = matcherTel.group();
            }
        }

        return phone;
    }

    private String getProvinceBaseId(String provinceName) {
        if(StrUtil.isEmpty(provinceName)) {
            return "";
        }
        String provinceBaseId = sysAreaMapper.getProvinceBaseId(provinceName);
        if(StrUtil.isEmpty(provinceBaseId)) {
            return "";
        }
        return provinceBaseId;
    }

    private String getCityOrCountyBaseId(String cityOrCountyName, String provinceBaseId) {
        if(StrUtil.isEmpty(cityOrCountyName) || StrUtil.isEmpty(provinceBaseId)) {
            return "";
        }
        String cityOrCountyBaseId = sysAreaMapper.getCityOrCountyBaseId(cityOrCountyName, provinceBaseId);
        if(StrUtil.isEmpty(cityOrCountyBaseId)) {
            return "";
        }
        return cityOrCountyBaseId;
    }

    /**
     * 通过询价单创建商机
     * @param sourcingDemandVo 询价单信息
     * @param supplyToCRMParamDto 页面参数
     * @param customerId 关联客户的id
     * @param userId
     * @return
     */
    private CommunicateInfo buildCommunicateInfoBySourcingDemand(SourcingDemandVo sourcingDemandVo,SupplyToCRMParamDto supplyToCRMParamDto, String customerId, String userId, String realname) {
        CommunicateInfo communicateInfo = new CommunicateInfo();
        communicateInfo.setBaseId(IdUtil.simpleUUID());
        communicateInfo.setProductName(sourcingDemandVo.getBaseName());
        // 关联客户
        communicateInfo.setCustomerId(customerId);
        // 商机获取时间
        communicateInfo.setBusinessAquireTime(new Date());
        // 初步接洽
        communicateInfo.setCommunicateStatus(SupplyToCRMConstant.COMMUNICATE_STATUS_1);
        // 普通机会
        communicateInfo.setCommunicateType(SupplyToCRMConstant.COMMUNICATE_TYPE_1);
        // 商机来源 其他
        communicateInfo.setCommunicateSource(SupplyToCRMConstant.COMMUNICATE_SOURCE_8);

        // 其他非表单字段
        communicateInfo.setCreator(userId);
        communicateInfo.setBaseCreateTime(new Date());
        // 后台新增的类型
        communicateInfo.setType("2");
        communicateInfo.setCompanyId(supplyToCRMParamDto.getCompanyId());

        communicateInfo.setCommunicateFrom(supplyToCRMParamDto.getSourceFrom());
        communicateInfo.setCommunicateFromBaseId(supplyToCRMParamDto.getBaseId());
        communicateInfo.setSupplyUrl(supplyToCRMParamDto.getSupplyUrl());
        communicateInfo.setDirectorId(userId);
        communicateInfo.setDirectorName(realname);
        communicateInfo.setDeptId(supplyToCRMParamDto.getDeptId());
        communicateInfo.setCompanyName(supplyToCRMParamDto.getCompanyName());
        return communicateInfo;
    }

    /**
     * 通过招募单创建商机
     * @param sourcingDemandVo 询价单信息
     * @param supplyToCRMParamDto 页面参数
     * @param customerId 关联客户的id
     * @param userId
     * @return
     */
    private CommunicateInfo buildCommunicateInfoByRecruitment(LuLianRecruitment recruitment, SupplyToCRMParamDto supplyToCRMParamDto, String customerId, String userId, String realname) {
        CommunicateInfo communicateInfo = new CommunicateInfo();
        communicateInfo.setBaseId(IdUtil.simpleUUID());
        communicateInfo.setProductName(recruitment.getDemandName());
        // 关联客户
        communicateInfo.setCustomerId(customerId);
        // 商机获取时间
        communicateInfo.setBusinessAquireTime(new Date());
        // 初步接洽
        communicateInfo.setCommunicateStatus(SupplyToCRMConstant.COMMUNICATE_STATUS_1);
        // 普通机会
        communicateInfo.setCommunicateType(SupplyToCRMConstant.COMMUNICATE_TYPE_1);
        // 商机来源 其他
        communicateInfo.setCommunicateSource(SupplyToCRMConstant.COMMUNICATE_SOURCE_8);

        // 其他非表单字段
        communicateInfo.setCreator(userId);
        communicateInfo.setBaseCreateTime(new Date());
        // 后台新增的类型
        communicateInfo.setType("2");
        communicateInfo.setCompanyId(supplyToCRMParamDto.getCompanyId());

        communicateInfo.setCommunicateFrom(supplyToCRMParamDto.getSourceFrom());
        communicateInfo.setCommunicateFromBaseId(supplyToCRMParamDto.getBaseId());
        communicateInfo.setSupplyUrl(supplyToCRMParamDto.getSupplyUrl());
        communicateInfo.setDirectorId(userId);
        communicateInfo.setDirectorName(realname);
        communicateInfo.setDeptId(supplyToCRMParamDto.getDeptId());
        communicateInfo.setCompanyName(supplyToCRMParamDto.getCompanyName());
        return communicateInfo;
    }

    private CommunicateInfo buildCommunicateInfoBySupplierInquiryOrder(LuLianSupplierInquiryOrder supplierInquiryOrder, SupplyToCRMParamDto supplyToCRMParamDto, String customerId, String userId, String realname) {
        CommunicateInfo communicateInfo = new CommunicateInfo();
        communicateInfo.setBaseId(IdUtil.simpleUUID());
        communicateInfo.setProductName(supplierInquiryOrder.getBaseName());
        // 关联客户
        communicateInfo.setCustomerId(customerId);
        // 商机获取时间
        communicateInfo.setBusinessAquireTime(new Date());
        // 初步接洽
        communicateInfo.setCommunicateStatus(SupplyToCRMConstant.COMMUNICATE_STATUS_1);
        // 普通机会
        communicateInfo.setCommunicateType(SupplyToCRMConstant.COMMUNICATE_TYPE_1);
        // 商机来源 其他
        communicateInfo.setCommunicateSource(SupplyToCRMConstant.COMMUNICATE_SOURCE_8);

        // 其他非表单字段
        communicateInfo.setCreator(userId);
        communicateInfo.setBaseCreateTime(new Date());
        // 后台新增的类型
        communicateInfo.setType("2");
        communicateInfo.setCompanyId(supplyToCRMParamDto.getCompanyId());

        communicateInfo.setCommunicateFrom(supplyToCRMParamDto.getSourceFrom());
        communicateInfo.setCommunicateFromBaseId(supplyToCRMParamDto.getBaseId());
        communicateInfo.setSupplyUrl(supplyToCRMParamDto.getSupplyUrl());
        communicateInfo.setDirectorId(userId);
        communicateInfo.setDirectorName(realname);
        communicateInfo.setDeptId(supplyToCRMParamDto.getDeptId());
        communicateInfo.setCompanyName(supplyToCRMParamDto.getCompanyName());
        return communicateInfo;
    }

    private CommunicateInfo buildCommunicateInfoByBidInfo(Map<String, String> map, SupplyToCRMParamDto supplyToCRMParamDto, String customerId, String userId, String realname) {
        CommunicateInfo communicateInfo = new CommunicateInfo();
        communicateInfo.setBaseId(IdUtil.simpleUUID());
        communicateInfo.setProductName(map.get("projectName"));
        // 关联客户
        communicateInfo.setCustomerId(customerId);
        // 商机获取时间
        communicateInfo.setBusinessAquireTime(new Date());
        // 初步接洽
        communicateInfo.setCommunicateStatus(SupplyToCRMConstant.COMMUNICATE_STATUS_1);
        // 普通机会
        communicateInfo.setCommunicateType(SupplyToCRMConstant.COMMUNICATE_TYPE_1);
        // 商机来源 其他
        communicateInfo.setCommunicateSource(SupplyToCRMConstant.COMMUNICATE_SOURCE_8);

        // 其他非表单字段
        communicateInfo.setCreator(userId);
        communicateInfo.setBaseCreateTime(new Date());
        // 后台新增的类型
        communicateInfo.setType("2");
        communicateInfo.setCompanyId(supplyToCRMParamDto.getCompanyId());

        communicateInfo.setCommunicateFrom(supplyToCRMParamDto.getSourceFrom());
        communicateInfo.setCommunicateFromBaseId(supplyToCRMParamDto.getBaseId());
        communicateInfo.setSupplyUrl(supplyToCRMParamDto.getSupplyUrl());
        communicateInfo.setDirectorId(userId);
        communicateInfo.setDirectorName(realname);
        communicateInfo.setDeptId(supplyToCRMParamDto.getDeptId());
        communicateInfo.setCompanyName(supplyToCRMParamDto.getCompanyName());
        return communicateInfo;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Message addCRM(SupplyToCRMParamDto supplyToCRMParamDto, String userId) {
//        List<String> msg = new ArrayList<>();
        Message userInfoMessage = cloudShowManagerSubService.getUserInfo(userId);
        if (userInfoMessage.getCode() != MessageCodeConstant.MSG_SUCCESS_CODE) {
            throw new BusinessException("获取用户信息失败");
        }
        Object obj = userInfoMessage.getObj();
        if (obj == null) {
            throw new BusinessException("获取用户信息异常");
        }
        Map<String, Object> userInfoMap = (Map<String, Object>) obj;
//        log.info("用户信息：{}", userInfoMap);
        String realname = (String) userInfoMap.get("realname");
        String deptId = (String)userInfoMap.get("deptId");
        String deptName = (String)userInfoMap.get("deptName");
        supplyToCRMParamDto.setDeptId(deptId);
        supplyToCRMParamDto.setDeptName(deptName);
        LuLianEnterprise luLianEnterprise = luLianEnterpriseService.getById(supplyToCRMParamDto.getCompanyId());
        if(luLianEnterprise == null) {
            throw new BusinessException("用户所属企业不存在");
        }else{
            supplyToCRMParamDto.setCompanyName(luLianEnterprise.getBaseName());
        }

        List<Map<String, String>> params = supplyToCRMParamDto.getParams();
        for (Map<String, String> param : params) {
            String name = param.get("name");
            String linkPhone = param.get("linkPhone");
            String contacts = param.get("contacts");
            if(name == null || name.isEmpty()) {
                return Message.fail("选择的数据中存在无效客户名称");
            }
            if(linkPhone == null || linkPhone.isEmpty()) {
                return Message.fail("选择的数据中存在无效联系方式");
            }
            // 判断客户是否存在
            int customerCount = customerManagementMapper.queryCustomerCountByEnterpriseName(name, supplyToCRMParamDto.getCompanyId());
            if(customerCount > 0) {
                return Message.fail("「" + name + "」"  + "客户已存在");
            }
            // 创建客户
            CustomerManagement customerManagement = new CustomerManagement();
            customerManagement.setBaseId(IdUtil.simpleUUID());
            customerManagement.setEnterpriseName(name);
            customerManagement.setPhone(linkPhone);
            customerManagement.setCustomerStatus(SupplyToCRMConstant.DEFAULT_CUSTOMER_STATUS);
            customerManagement.setCustomerFrom(supplyToCRMParamDto.getSourceFrom());
            customerManagement.setCreator(userId);
            customerManagement.setBaseCreateTime(new Date());
            customerManagement.setCompanyId(supplyToCRMParamDto.getCompanyId());
            customerManagement.setSaleResponsiblePerson(userId);
            customerManagement.setDeptId(supplyToCRMParamDto.getDeptId());
            customerManagementMapper.insert(customerManagement);

            // 创建联系人，并将其与客户进行关联
            customerContactsService.createContactAndRelation(contacts, linkPhone, customerManagement.getBaseId(), userId, supplyToCRMParamDto.getCompanyId(), supplyToCRMParamDto);
        }
        return Message.success("添加成功");
    }

    @Override
    public Boolean isCustomerExist(String companyId, String name) {
        // 判断客户是否存在
        int customerCount = customerManagementMapper.queryCustomerCountByEnterpriseName(name, companyId);
        return customerCount > 0;
    }
}
